package com.yuand.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import com.yuand.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author yuandong
 * @date 2021/8/20 10:19
 */
@Slf4j
public class HttpUtils {

    /**
     * 获取请求头header中的参数
     * TreeMap实现了SortedMap接口，保证了有序性。默认的排序是根据key值进行升序排序
     * @param request
     * @return
     */
    public static SortedMap<String, String> getHeaderParams(HttpServletRequest request) throws IOException {
        SortedMap<String, String> sortedMap = new TreeMap<>();
        //获取Header上的参数
        //appKey
        String appKey = request.getHeader(Constant.APP_KEY);
        sortedMap.put(Constant.APP_KEY, appKey);

        //时间戳,增加链接的有效时间,超过阈值,即失效
        String timestamp = request.getHeader(Constant.TIME_STAMP);
        sortedMap.put(Constant.TIME_STAMP, timestamp);

        //获取调用方的签名
        String sign = request.getHeader(Constant.SIGN);
        sortedMap.put(Constant.SIGN, sign);

        // 临时流水号,防止重复提交
        String nonce = request.getHeader(Constant.NONCE);
        sortedMap.put(Constant.NONCE, nonce);

        //请求路径: 如 http:localhost:8080/report/data/report
        //String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getServletPath();
        String url = request.getServletPath();
        sortedMap.put(Constant.REQ_URL, url);


       /* // 分别获取了request inputstream中的body信息、parameter信息
        //获取body（对应@RequestBody）
        if (request instanceof BodyReaderHttpServletRequestWrapper) {
            BodyReaderHttpServletRequestWrapper requestWrapper = (BodyReaderHttpServletRequestWrapper) request;
            try {
                JSONObject data = JSONObject.parseObject(requestWrapper.getBody());
                if (data != null) {
                    //获取POST请求的JSON参数,以键值对形式保存
                    for (Map.Entry<String, Object> entry : data.entrySet()) {
                        sortedMap.put(entry.getKey(), entry.getValue().toString());
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }*/
        return sortedMap;
    }


    /**
     * 获取url中的参数,该参数使用LinkedHashMap接收
     * @param request
     * @return
     */
    public static LinkedHashMap<String, List<String>> getUrlParams(HttpServletRequest request) {

        LinkedHashMap<String, List<String>> params = new LinkedHashMap<>();

        if (!CollectionUtils.isEmpty(request.getParameterMap())) {

            Map<String, String[]> parameterMap = request.getParameterMap();

            //获取GET请求参数,以键值对形式保存
            for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {//{username:[xx],password:[xx]}
                for (String value : entry.getValue()) {
                    if(value.indexOf(",")==-1){
                        params.put(entry.getKey(), Lists.newArrayList(entry.getValue()));
                    }else{
                        String[] split = value.split(",");
                        params.put(entry.getKey(),Lists.newArrayList(split));
                    }
                }
            }
        }
        return params;
    }


    //获取post请求的请求体---body中的数据
    public static String getRequestBody(HttpServletRequest request) throws IOException {
        // 分别获取了request inputstream中的body信息、parameter信息
        //获取body（对应@RequestBody）
        if (request instanceof BodyReaderHttpServletRequestWrapper) {
            BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
            try {
                JSONObject data = JSONObject.parseObject(requestWrapper.getBody());
                if (data != null) {
                    //获取POST请求的JSON参数,以键值对形式保存
                    for (Map.Entry<String, Object> entry : data.entrySet()) {
                        System.out.println("key>>>>" + entry.getKey() + "value>>>" + entry.getValue().toString());
                    }
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            return requestWrapper.getBody();
        } else {
            return "";
        }
    }
}
